<template>
    <view class="home-box p20box linear-bg">
        <up-navbar title="蕴明计划维修管理系统" placeholder>
            <template #left> <text style="color: #fff">></text> </template>
        </up-navbar>
        <!-- {{ msg }} -->
        <view class="user-box">
            <view class="info-box">
                <view class="username">你好，张三</view>
                <view class="role">
                    <up-tag text="电工" size="mini" type="warning"></up-tag>
                </view>
            </view>
            <view class="date-box">
                <text class="data">{{ currentDate }}</text>
                <text class="week">{{ currentWeek }}</text>
            </view>
        </view>
        <view class="tasks-box">
            <view class="task-box" v-for="item in 2">
                <view class="task-head">
                    <view class="title">天窗维修</view>
                </view>
                <view class="task-info">
                    <view class="info-item">报修人：张三</view>
                    <view class="info-item">事件描述：天窗无法打开</view>
                    <view class="info-item">报修时间：张三</view>
                    <view class="info-item">状态：未完成</view>
                </view>
                <view class="task-operate">
                    <up-button
                        style="width: auto; margin: 0; margin-right: 10rpx"
                        type="primary"
                        text="详情"
                        size="small"
                        @click="onTaskClick"
                    ></up-button>
                    <up-button
                        style="width: auto; margin: 0"
                        type="primary"
                        text="下载"
                        size="small"
                        @click="downloadFile"
                    ></up-button>
                </view>
            </view>
        </view>

        <up-tabbar
            :value="data.currentPage"
            @change="onPageChange"
            :fixed="true"
            :placeholder="true"
            :safeAreaInsetBottom="true"
        >
            <up-tabbar-item
                text="首页"
                icon="home"
                name="home"
            ></up-tabbar-item>
            <up-tabbar-item
                text="我的"
                icon="account"
                name="user"
            ></up-tabbar-item>
        </up-tabbar>
    </view>
</template>

<script setup>
import { computed, reactive, ref } from 'vue';
import dayjs from 'dayjs';
// import { downloadFile } from '@/utils/download.js';

// 响应式变量
const isDownloading = ref(false);
const downloadProgress = ref(0);
const resultMessage = ref('');

// 检查并请求存储权限
const checkPermission = async () => {
    if (uni.getSystemInfoSync().platform === 'android') {
        const androidVersion = parseInt(
            uni.getSystemInfoSync().system.split(' ')[1]
        );
        // Android 10及以上不需要申请存储权限
        if (androidVersion >= 10) {
            return true;
        }

        // 检查权限
        const res = await uni.requestPermissions({
            permissions: ['android.permission.WRITE_EXTERNAL_STORAGE'],
        });

        return res[0].grantStatus === 1;
    }
    return true;
};
let msg = ref('');

// 下载文件
const downloadFile = async () => {
    // 要下载的文件URL（替换为实际文件地址）
    const fileUrl = '/static/ABS保理系统操作手册.docx';
    // 文件名（替换为实际文件名）
    const fileName = 'example.pdf';
    msg.value = '开始下载1...';
    // 检查权限
    const hasPermission = await checkPermission();
    if (!hasPermission) {
        resultMessage.value = '请授予存储权限以继续下载';
        return;
    }
    msg.value = '开始下载2...';

    isDownloading.value = true;
    resultMessage.value = '';
    downloadProgress.value = 0;

    try {
        // 下载文件
        const downloadTask = uni.downloadFile({
            url: fileUrl,
            success: (downloadResult) => {
                msg.value = '开始下载3...';
                if (downloadResult.statusCode === 200) {
                    // 保存文件
                    uni.saveFile({
                        tempFilePath: downloadResult.tempFilePath,
                        success: (saveResult) => {
                            isDownloading.value = false;
                            resultMessage.value = `文件已保存至：${saveResult.savedFilePath}`;
                            // 提示用户
                            uni.showToast({
                                title: '下载成功',
                                icon: 'success',
                                duration: 2000,
                            });
                        },
                        fail: (err) => {
                            isDownloading.value = false;
                            resultMessage.value = `保存失败：${err.errMsg}`;
                        },
                    });
                } else {
                    isDownloading.value = false;
                    resultMessage.value = `下载失败，状态码：${downloadResult.statusCode}`;
                }
            },
            fail: (err) => {
                msg.value = '开始下载4...';
                isDownloading.value = false;
                resultMessage.value = `下载失败：${err.errMsg}`;
            },
        });
        msg.value = '开始下载5...';
        // 监听下载进度
        downloadTask.onProgressUpdate((res) => {
            downloadProgress.value = res.progress;
        });
    } catch (err) {
        msg.value = '开始下载6...';
        isDownloading.value = false;
        resultMessage.value = `发生错误：${err.message}`;
    }
};

const data = reactive({
    form: {},
    currentPage: 'home',
});

const currentDate = computed(() => {
    return dayjs().format('MM-DD');
});

const currentWeek = computed(() => {
    const num = dayjs().day();
    switch (num) {
        case 1:
            return '周一';
        case 2:
            return '周二';
        case 3:
            return '周三';
        case 4:
            return '周四';
        case 5:
            return '周五';
        case 6:
            return '周六';
        case 7:
            return '周日';
    }
});

const onTaskClick = () => {
    uni.navigateTo({
        url: '/pages/home/forms/step0',
    });
};
const onTaskDownloadClick = () => {
    uni.showToast({
        title: '下载中...',
        icon: 'loading',
        duration: 1000,
    });
};

const onPageChange = (e) => {
    uni.navigateTo({
        url: '/pages/user/user',
    });
};
</script>

<style lang="scss">
.home-box {
    padding-top: 40rpx;
    .user-box {
        .info-box {
            display: flex;
            .username {
                font-size: 18px;
                margin-right: 10rpx;
            }
            .role {
            }
        }
        .date-box {
            font-size: 14px;
            color: #b5bec9;
            .data {
            }
            .week {
                margin-left: 10rpx;
            }
        }
    }
    .tasks-box {
        margin-top: 30rpx;
        .task-box {
            border-radius: 16rpx;
            background-color: #fff;
            margin-bottom: 40rpx;
            .task-head {
                padding: 20rpx;
                background-color: #f5f9ff;
            }
            .task-info {
                padding: 20rpx;
            }
            .task-operate {
                display: flex;
                justify-content: flex-end;
                padding: 0 20rpx 20rpx;
            }
            &:last-child {
                margin-bottom: 0;
            }
        }
    }
}
</style>
